package com.wzw.springboot.principle.scheduler;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTask;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

/**
 * @author Wangzhiwen
 */
@Component
public class SchedulePrinciple implements SchedulingConfigurer {

    @Resource
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    @Resource
    private RedissonClient redissonClient;

    private final Map<String, ScheduledFuture<?>> taskMap = new ConcurrentHashMap<>(32);

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        RLock lock = redissonClient.getLock("11");
        lock.tryLock()
        // 启动时扫表加入基于Corn表达式的任务
        taskRegistrar.addCronTask(new IncludeIdCornTask("1", () -> {
        }, ""));
        Iterator<ScheduledTask> iterator = taskRegistrar.getScheduledTasks().iterator();
        while (iterator.hasNext()) {
            ScheduledTask scheduledTask = iterator.next();
            IncludeIdCornTask task = (IncludeIdCornTask) scheduledTask.getTask();
            // 匹配
            if ("1".equals(task.getId())) {
                // 先停止在修改还
                scheduledTask.cancel();
                iterator.remove();
            }
        }

    }

    public void addTask(String id) {
        // 使用线程池维护
        Runnable runnable = () -> {
        };
        CronTrigger cronTrigger = new CronTrigger("");
        ScheduledFuture<?> schedule = threadPoolTaskScheduler.schedule(runnable, cronTrigger);
        taskMap.put(id, schedule);
        threadPoolTaskScheduler.shutdown();
    }

    public void removeTask(String id) {
        ScheduledFuture<?> remove = taskMap.remove(id);
        remove.cancel(true);
    }

    public void updateTask(String id) {
        if (!taskMap.containsKey(id)) {
            return;
        }
    }
}
